package com.youseu.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Tao
 * @version 1.0
 * 自定义校验器 验证传入的值是否在values中
 */
public class EnumConstraintValidator implements ConstraintValidator<EnumValidate,Integer> {
    Set<Integer> set = new HashSet<>();
    String regexp = "";
    @Override
    public void initialize(EnumValidate constraintAnnotation) {
        int[] values = constraintAnnotation.values();//注解设置的values
        for (int value : values) {
            set.add(value);
        }
        regexp = constraintAnnotation.regexp();
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        //integer是字段传入的真正的值
        // return integer.toString().matches(regexp);
        return set.contains(integer);
    }
}
